[[...path]].page.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import React, { useEffect } from 'react';
  2. import { type IUserHasId, type IPagePopulatedToShowRevision, getIdForRef } from '@growi/core';
  3. import type {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import Head from 'next/head';
  8. import superjson from 'superjson';
  9. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  10. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  11. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  12. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  13. import { ShareLinkPageView } from '~/components/ShareLinkPageView';
  14. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  15. import type { CrowiRequest } from '~/interfaces/crowi-request';
  16. import type { RendererConfig } from '~/interfaces/services/renderer';
  17. import type { IShareLinkHasId } from '~/interfaces/share-link';
  18. import type { PageDocument } from '~/server/models/page';
  19. import ShareLink from '~/server/models/share-link';
  20. import {
  21. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  22. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid, useIsEnabledMarp,
  23. } from '~/stores/context';
  24. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  25. import loggerFactory from '~/utils/logger';
  26. import type { NextPageWithLayout } from '../_app.page';
  27. import {
  28. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, CommonProps, skipSSR,
  29. } from '../utils/commons';
  30. const logger = loggerFactory('growi:next-page:share');
  31. type Props = CommonProps & {
  32. shareLinkRelatedPage?: IShareLinkRelatedPage,
  33. shareLink?: IShareLinkHasId,
  34. isNotFound: boolean,
  35. isExpired: boolean,
  36. disableLinkSharing: boolean,
  37. isSearchServiceConfigured: boolean,
  38. isSearchServiceReachable: boolean,
  39. isSearchScopeChildrenAsDefault: boolean,
  40. isEnabledMarp: boolean,
  41. drawioUri: string | null,
  42. rendererConfig: RendererConfig,
  43. skipSSR: boolean,
  44. ssrMaxRevisionBodyLength: number,
  45. };
  46. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  47. superjson.registerCustom<IShareLinkRelatedPage, string>(
  48. {
  49. isApplicable: (v): v is IShareLinkRelatedPage => {
  50. return v != null
  51. && v.toObject != null
  52. && v.lastUpdateUser != null
  53. && v.creator != null
  54. && v.revision != null;
  55. },
  56. serialize: (v) => { return superjson.stringify(v.toObject()) },
  57. deserialize: (v) => { return superjson.parse(v) },
  58. },
  59. 'IShareLinkRelatedPageTransformer',
  60. );
  61. // GrowiContextualSubNavigation for shared page
  62. // get page info from props not to send request 'GET /page' from client
  63. type GrowiContextualSubNavigationForSharedPageProps = {
  64. page?: IPagePopulatedToShowRevision,
  65. isLinkSharingDisabled: boolean,
  66. }
  67. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  68. const { page, isLinkSharingDisabled } = props;
  69. return (
  70. <div data-testid="grw-contextual-sub-nav">
  71. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled} />
  72. </div>
  73. );
  74. };
  75. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  76. useCurrentPathname(props.shareLink?.relatedPage.path);
  77. useIsSearchPage(false);
  78. useIsNotFound(props.isNotFound);
  79. useShareLinkId(props.shareLink?._id);
  80. useCurrentPageId(props.shareLink?.relatedPage._id);
  81. useCurrentUser(props.currentUser);
  82. useRendererConfig(props.rendererConfig);
  83. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  84. useIsSearchServiceReachable(props.isSearchServiceReachable);
  85. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  86. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  87. useIsContainerFluid(props.isContainerFluid);
  88. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  89. useEffect(() => {
  90. if (!props.skipSSR) {
  91. return;
  92. }
  93. if (props.shareLink?.relatedPage._id != null && !props.isNotFound) {
  94. mutateCurrentPage();
  95. }
  96. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  97. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(props.shareLinkRelatedPage);
  98. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  99. const title = generateCustomTitleForPage(props, pagePath);
  100. return (
  101. <>
  102. <Head>
  103. <title>{title}</title>
  104. </Head>
  105. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  106. <header className="py-0 position-relative">
  107. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  108. </header>
  109. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  110. <ShareLinkPageView
  111. pagePath={pagePath}
  112. rendererConfig={props.rendererConfig}
  113. page={currentPage ?? props.shareLinkRelatedPage}
  114. shareLink={props.shareLink}
  115. isExpired={props.isExpired}
  116. disableLinkSharing={props.disableLinkSharing}
  117. />
  118. </div>
  119. </>
  120. );
  121. };
  122. SharedPage.getLayout = function getLayout(page) {
  123. return (
  124. <>
  125. <DrawioViewerScript />
  126. <ShareLinkLayout>{page}</ShareLinkLayout>
  127. </>
  128. );
  129. };
  130. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  131. const req: CrowiRequest = context.req as CrowiRequest;
  132. const { crowi } = req;
  133. const { configManager, searchService } = crowi;
  134. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  135. props.isSearchServiceConfigured = searchService.isConfigured;
  136. props.isSearchServiceReachable = searchService.isReachable;
  137. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  138. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  139. props.rendererConfig = {
  140. isSharedPage: true,
  141. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  142. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  143. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  144. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  145. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  146. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  147. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  148. // XSS Options
  149. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  150. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  151. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  152. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  153. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  154. };
  155. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  156. }
  157. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  158. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  159. props._nextI18Next = nextI18NextConfig._nextI18Next;
  160. }
  161. function getAction(props: Props): SupportedActionType {
  162. let action: SupportedActionType;
  163. if (props.isExpired) {
  164. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  165. }
  166. else if (props.shareLink == null) {
  167. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  168. }
  169. else {
  170. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  171. }
  172. return action;
  173. }
  174. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  175. const req: CrowiRequest = context.req as CrowiRequest;
  176. const parameters = {
  177. ip: req.ip,
  178. endpoint: req.originalUrl,
  179. action,
  180. user: req.user?._id,
  181. snapshot: {
  182. username: req.user?.username,
  183. },
  184. };
  185. await req.crowi.activityService.createActivity(parameters);
  186. }
  187. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  188. const req = context.req as CrowiRequest<IUserHasId & any>;
  189. const { crowi, params } = req;
  190. const result = await getServerSideCommonProps(context);
  191. if (!('props' in result)) {
  192. throw new Error('invalid getSSP result');
  193. }
  194. const props: Props = result.props as Props;
  195. try {
  196. const shareLink = await ShareLink.findOne({ _id: params.linkId }).populate('relatedPage');
  197. if (shareLink == null) {
  198. props.isNotFound = true;
  199. }
  200. else {
  201. props.isNotFound = false;
  202. props.isExpired = shareLink.isExpired();
  203. props.shareLink = shareLink.toObject();
  204. // retrieve Page
  205. const Page = crowi.model('Page');
  206. const relatedPage = await Page.findOne({ _id: getIdForRef(shareLink.relatedPage) });
  207. // determine whether skip SSR
  208. const ssrMaxRevisionBodyLength = crowi.configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  209. props.skipSSR = await skipSSR(relatedPage, ssrMaxRevisionBodyLength);
  210. // populate
  211. props.shareLinkRelatedPage = await relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  212. }
  213. }
  214. catch (err) {
  215. logger.error(err);
  216. }
  217. injectServerConfigurations(context, props);
  218. await injectNextI18NextConfigurations(context, props);
  219. await addActivity(context, getAction(props));
  220. return {
  221. props,
  222. };
  223. };
  224. export default SharedPage;